package cn.zf233.xcloud.intercept;

import cn.zf233.xcloud.commom.Const;
import cn.zf233.xcloud.commom.R;
import cn.zf233.xcloud.util.JsonUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zf233 on 2020/11/4
 * 用户拦截 有些请求需要返回Json
 */
public class PermissionCheck implements HandlerInterceptor {


    private static final Map<String, String> RESPONSE_JSON_OF_INTERCEPT_URI;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object current = request.getSession().getAttribute(Const.CURRENT_USER);
        if (current != null) {
            return true;
        }
        String targetUri = request.getRequestURI();
        if (!RESPONSE_JSON_OF_INTERCEPT_URI.containsKey(targetUri)) {
            response.setContentType("text/json; charset=UTF-8");
            response.getWriter().println(JsonUtil.toJson(R.createByErrorIllegalArgument("登陆失效，请重新登录")));
        } else {
            response.sendRedirect("/user/jump/index");
        }
        return false;
    }

    static {
        String[] uriArray = {
                "/user/quit",
                "/user/jump",

                "/share/get",
        };
        RESPONSE_JSON_OF_INTERCEPT_URI = new HashMap<>(uriArray.length);
        Arrays.stream(uriArray).forEach(uri -> RESPONSE_JSON_OF_INTERCEPT_URI.put(uri, uri));
    }
}
